/***************************************************
> Copyright (C) 2023 ==lv== All rights reserved.
> File Name: threadpool.c
> Author: lv
> Mail:joseph2009@163.com 
> Created Time: 2023年12月09日 星期六 14时52分11秒
***************************************************/

#include "threadpool.h"

//临界资源
int run_flag = 1;
//消费者线程
void*cousumer(void*arg)
{
	threadPool*pool_c = (threadPool*)arg;
	int dat = 0;
	while(run_flag == 1)
    {
        sem_wait(&pool_c->rsem);
        if(run_flag == 0) 
			break;
        pthread_mutex_lock(&pool_c->mutex);
        //读取数据
		dat = pop(pool_c->que);
		printf("cousumer:%d\n",dat);		
        pthread_mutex_unlock(&pool_c->mutex);
        sem_post(&pool_c->wsem);
		
		//read()
		sleep(1);
    }
	pthread_exit(NULL);
}
threadPool* createThreadPool(int thread_count,int queue_max_deep)
{
	
	threadPool * pool = NULL;
	int i = 0;
	int ret = 0;
	//动态申请空间
	pool = (threadPool*)malloc(sizeof(threadPool));
	memset(pool,0,sizeof(threadPool));
	
	//动态分配存放线程编号的空间
	pool->tids = (pthread_t*)malloc(sizeof(pthread_t)*thread_count);
	//que 成员获取值
	pool->que = create_queue();
    //线程数量和最大任务数量赋值。
	pool->max_tasks = queue_max_deep;
	pool->threads = thread_count;
    //两个信号量和锁初始化
	pthread_mutex_init(&pool->mutex,NULL);
	sem_init(&pool->rsem,0,0);
	sem_init(&pool->wsem,0,pool->max_tasks);
    //创建 n 个线程
    for(i = 0;i < thread_count;i++)
    {
        ret = pthread_create(&pool->tids[i],NULL,cousumer,(void*)pool);
		if(ret!=0)
		{
			printf("%s\n",strerror(ret));
			exit(1);
		}
    }
    return pool;
}


void destroyThreadPool(threadPool *pool)
{
	 //释放信号量
	 sem_destroy(&pool->rsem);
	 sem_destroy(&pool->wsem);
     //释放锁
	 pthread_mutex_destroy(&pool->mutex);
     //释放存放线程 id 的空间
	 free(pool->tids);
	 pool->tids = NULL;
     //释放 pool 指向空间
	 free(pool);
	 pool = NULL;
}
